package com.topteam.component.freemarker;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import com.topteam.frame.controllor.BaseController;
import com.topteam.security.UserSession;
import com.topteam.utility.StringUtil;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 带有权限控制显隐的按钮
 * @author Jiang Feng
 *
 */
public class TopButton extends TopTemplateModel{
	
	public static final String TAG = "button";
	
	private BaseController controller;
	
	private String id;
	
	private String icon;
	
	private String iconAlign;
	
	private String url;
	
	private String text;
	
	private boolean plain;
	
	private String onclick;
	
	private String oncomplete;
	
	private String formid;
	
	private boolean show = true;
	
	private boolean needAuth;
	
	public TopButton(BaseController controller){
		this.controller = controller;
	}
	
	private void initPara(Map para, Environment env) throws TemplateException{
		url = getStrPara("url", para, env);
		if(StringUtil.isNotNull(url)){
			needAuth = true;
		}
		UserSession userSession = controller.getUserSession();
		show = userSession.authBtn(url);
		id = getStrPara("id", para, env);
		if(StringUtil.isNull(id)){
			throw new TemplateException("必须直接按钮id的值", env);
		}
		icon = getStrPara("icon", para, env);
		iconAlign = getStrPara("iconAlign", para, env);
		text = getStrPara("text", para, env);
		plain = getBoolPara("plain", para, env,plain);
		onclick = getStrPara("onclick", para, env);
		oncomplete = getStrPara("oncomplete", para, env);
		formid = getStrPara("formid", para, env);
	}

	@Override
	public void execute(Environment env, Map para, TemplateModel[] arg2,
			TemplateDirectiveBody arg3) throws TemplateException, IOException {
		initPara(para,env);
		Writer w = env.getOut();
		if(needAuth&&!show){
			return;
		}
		w.write("<a href=\"#\" class=\"easyui-linkbutton\" ");
		if(StringUtil.isNotNull(icon)){
			w.write(" iconCls=\"icon-"+icon+"\" ");
		}
		if(StringUtil.isNotNull(id)){
			w.write(" id=\""+id+"\" ");
		}
		if(StringUtil.isNotNull(iconAlign)){
			w.write(" iconAlign=\""+iconAlign+"\" ");
		}
		if(plain){
			w.write("  plain=\""+String.valueOf(plain)+"\"");
		}
		
		w.write(" >");
		w.write(text);
		w.write("</a>");
		writeScript(w);
	}
	
	public void writeScript(Writer w) throws IOException{
		w.write("<script type=\"text/javascript\">");
		w.write("$(function(){  $('#"+id+"').bind('click', function(){\r\n");
		if(StringUtil.isNotNull(onclick))
			w.write(onclick+"('"+url+"');\r\n");
		if(StringUtil.isNotNull(formid)){
			w.write("$('#"+formid+"').form('submit'");
			if(StringUtil.isNotNull(oncomplete))
				w.write(",{success:function(args){"+oncomplete+"}}");
			w.write(");");
		}
		w.write("}); \r\n });");
		w.write("</script>");
	}

}
